package com.eol.service.merchant;

import com.eol.entity.dto.MerchantDto;
import com.eol.entity.po.merchant.ZMerchant;
import com.eol.mapper.business.merchant.ZMerchantMapper;
import com.eol.mapper.config.tkMybatis.MybatisBaseService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 商户表
 *
 * @author liulinhui
 * @email 1249055292@qq.com
 * @date 2020-06-05 20:53:41
 */
@Service
public class ZMerchantService extends MybatisBaseService<ZMerchantMapper, ZMerchant> {

    public List<MerchantDto> selectMerchantList(ZMerchant zMerchant) {
        return mapper.selectMerchantList(zMerchant);
    }

    public String selectMerchantIdByUserId(Long userId) {
        return mapper.selectMerchantIdByUserId(userId);
    }

    public Object buildTree(List<MerchantDto> list) {
        Set<MerchantDto> trees = new LinkedHashSet<>();
        Set<MerchantDto> depts = new LinkedHashSet<>();
        List<String> deptNames = list.stream().map(MerchantDto::getName).collect(Collectors.toList());
        boolean isChild;
        for (MerchantDto merchantDto : list) {
            isChild = false;
            if (StringUtils.isEmpty(merchantDto.getPid())) {
                trees.add(merchantDto);
            }
            for (MerchantDto it : list) {
                if (it.getPid().equals(merchantDto.getId())) {
                    isChild = true;
                    if (merchantDto.getChildren() == null) {
                        merchantDto.setChildren(new ArrayList<>());
                    }
                    merchantDto.getChildren().add(it);
                }
            }
            if (isChild)
                depts.add(merchantDto);
            else if (!deptNames.contains(this.selectById(merchantDto.getId()).getName()))
                depts.add(merchantDto);
        }

        if (CollectionUtils.isEmpty(trees)) {
            trees = depts;
        }

        Integer totalElements = list.size();

        Map<String, Object> map = new HashMap<>();
        map.put("totalElements", totalElements);
        map.put("content", CollectionUtils.isEmpty(trees) ? list : trees);
        return map;
    }
}